﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Polls;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetPolls()
		{
			List<MigrationPoll> output = new List<MigrationPoll>();

			IDictionary<string, PollsProvider> pollsProviders = PollManager.Providers;

			foreach (KeyValuePair<string, PollsProvider> pollsProvider in pollsProviders)
			{
				string providerName = pollsProvider.Key;
				PollManager pollManager = new PollManager(providerName);

				IList<IPollItem> polls = pollManager.GetAllPolls();

				foreach (IPollItem poll in polls)
				{
					MigrationPoll mp = new MigrationPoll();
					mp.Id = poll.ID;
					mp.Owner = poll.Owner;
					mp.ProviderName = providerName;
					mp.Title = poll.Title;
					mp.VoterNumber = poll.VoterNumber;

					foreach (IQuestionItem questionItem in poll.Questions)
					{
						MigrationPollQuestion mpq = new MigrationPollQuestion();
						mpq.Id = questionItem.ID;
						mpq.Layout = questionItem.Layout.ToString();
						mpq.SortOrder = questionItem.SortOrder;
						mpq.Text = questionItem.Text;

						foreach (IAnswerItem answerItem in questionItem.Answers)
						{
							MigrationPollAnswer mpa = new MigrationPollAnswer();
							mpa.ChartColor = answerItem.ChartColor;
							mpa.Id = answerItem.ID;
							mpa.Percentage = answerItem.Percentage;
							mpa.SortOrder = answerItem.SortOrder;
							mpa.Text = answerItem.Text;
							mpa.VoteCount = answerItem.VoteCount;

							mpq.Answers.Add(mpa);
						}

						mp.Questions.Add(mpq);
					}

					output.Add(mp);
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetPollsResponse", output);
		}
	}
}
